#!/usr/bin/python
#
# Copyright 2010 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This code is not supported by Google
#

"""Simple program to check if a particular item is serving in GCS using the 
SearchAPI for Shopping. 

see:
http://code.google.com/apis/shopping/search/v1/reference-overview.html
  
usage: 
    Edit this file and update the id, type cx, api key and  merchantID like:
    
    GCS_Serv_Check(id,type,'5968952','017227377487357491314:rspp7muevts',
                   'AIzaSyCTnn3ILOm89ce-ECtGZm-AgegGoXcNTXQ')      
    
    run with the ProvidedID (pid) GoogleID (gid), GTIN (gtin) of as an argument.
    
    The providedID is the unique ID number used by the merchant to identify
    an item in the feed.  PID format must be in
        channel:language:country:providedID
        
        --id=online:en:us:32123  --type=pid
        
    You can find the googleID number for an Item by either recalling it using
    the contentAPI or by inspecting the URL of that item in MerchantCenter 
    (eg, Merchant Center--> Products --> select that product; the docID is
    in the URL when you pull up the item).
    
        --id=7255011736617109478 --type=gid
        
    For GTIN queries, this script simply run &restrictBy=gtin=<gtin>&q=
        
        --id=00071766903409 --type=gtin        
    
    python gcs_serv_check.py --id= --type=gid|pid|gtin
    
"""

from xml.sax.saxutils import escape
import re
import getopt
import datetime
import xml.dom.minidom
import urllib,urllib2
import time
import sys
import logging
import libxml2


class GCS_Serv_Check(object):
  
  def log(self,msg, loglevel):
    LOG_FILENAME = 'gcs_check.log'
    logging.basicConfig(filename=LOG_FILENAME,level=logging.INFO)
    m = ('[%s] %s') % (datetime.datetime.now(), msg)
    print m
    if (loglevel == logging.DEBUG):
      logging.debug(m)       
    else:
      logging.info(m)
      
  def __init__(self, id, type, merchantid, cx, api_key): 
    self.id = id
    self.type = type
    self.cx = cx
    self.api_key = api_key
    self.merchantid = merchantid
    
    if (self.type == "gid"):
      url = ('https://www.googleapis.com/shopping/search/v1/cx:' + self.cx +
             '/products/' + self.merchantid + '/gid/' + self.id + '?alt=atom' 
             + '&key=' + self.api_key)
    elif (self.type == "pid"):
      url = ('https://www.googleapis.com/shopping/search/v1/cx:' + self.cx +
             '/products/' + self.merchantid + '/pid/' + self.id + '?alt=atom' 
             + '&key=' + self.api_key) 
    elif (self.type == "gtin"):  
      url = ('https://www.googleapis.com/shopping/search/v1/cx:' + self.cx +
             '/products?country=us&alt=atom&key=' + self.api_key + '&q='
             '&restrictBy=gtin='+ self.id)        
    else:
      self.log('--type= must be : gid|pid|gtin', logging.ERROR)
      sys.exit(0)
              
    self.log('Submitting: [' +  url + ']', logging.DEBUG)
      
    req = urllib2.Request(url)
    try:
      response = urllib2.urlopen(req)
    except urllib2.URLError, e:
      self.log('Server ERROR: item:[' + self.id + ']', logging.ERROR)
      return
    content = response.read()
    xmldoc = xml.dom.minidom.parseString(content)

    doc = libxml2.parseDoc(content)
    ctxt = doc.xpathNewContext()
    ctxt.xpathRegisterNs('openSearch', "http://a9.com/-/spec/opensearchrss/1.0/")
    ctxt.xpathRegisterNs('s', "http://www.google.com/shopping/api/schemas/2010")  
    ctxt.xpathRegisterNs('atom', "http://www.w3.org/2005/Atom")  
    ctxt.xpathRegisterNs('gd', "http://schemas.google.com/g/2005")
    
    if (self.type =='gid' or self.type =='pid'):
      n_providedId =  ctxt.xpathEval('/atom:entry/s:product/s:providedId')
      n_mod = ctxt.xpathEval('/atom:entry/s:product/s:modificationTime')
    if (self.type == 'gtin'):
      n_providedId =  ctxt.xpathEval('/atom:feed/atom:entry/s:product/s:providedId')
      n_mod = ctxt.xpathEval('/atom:feed/atom:entry/s:product/s:modificationTime')
            
    if (len(n_providedId) == 0):
      self.log('Not serving (no results)', logging.INFO)
      #self.log(xmldoc.toprettyxml(), logging.DEBUG)
    else:
      providedId = n_providedId[0].content
      mod = n_mod[0].content
      self.log('Item [' + providedId + '] is serving. Last Modified at: [' + mod + ']', logging.INFO)
    doc.freeDoc()
    ctxt.xpathFreeContext()
  
if __name__ == '__main__':
  id = None
  type = None

  try:
    opts, args = getopt.getopt(sys.argv[1:], None, ["id=","type="])
  except getopt.GetoptError:
    print 'Please specify --id=  --type=gid|pid|gtin'
    sys.exit(1)

  for opt, arg in opts:
    if opt == "--id":
      id = arg
    elif opt == "--type":
      type = arg

  if (id is not None  and type is not None):
    GCS_Serv_Check(id,type,'<YOUR_MERCHANT_ID>','<YOUR_CX_NUMBER>',
                   '<YOUR_API_KEY>')  
